package cn.com.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.com.entity.UserVo;
import cn.com.service.UserService;


@Configuration
@Controller
public class JDBCAuthController {
	Logger logger = LoggerFactory.getLogger(this.getClass().getName());

    @Autowired
    private DataSource dataSource;
    
//    @Autowired
//    private RedisConnectionFactory connectionFactory;
//    @Bean
//    public RedisTokenStore tokenStore() {
//        return new RedisTokenStore(connectionFactory);
//    }

    @Autowired
    UserService userService;  
    
    @RequestMapping("/")
    public String index() {
        return "index";
    } 
    @RequestMapping("/login")
    public String login() {
        return "login";
    }
    @RequestMapping("/index")
    public String hello() {
        return "hello";
    }
    
    
    @RequestMapping("/save")
    @ResponseBody
    public int save(String name,String password){  
        logger.info("save 开始");  
        int res = userService.save(new UserVo(null,name,password));  
        logger.info("save 结束"+res);  
        return res;  
    }  
      
    @RequestMapping("/q1")  
    @ResponseBody
    public UserVo q1(String name,HttpServletRequest req){  
        logger.info("q1 开始");  
        logger.info("q1 接收参数name={}",name);
        HttpSession session = req.getSession();
        logger.info("sessionId:"+session.getCreationTime()+"_"+session.getId());
        UserVo user = (UserVo) session.getAttribute("user");
        return user;  
    }  
      
    @RequestMapping("/q2") 
    @ResponseBody 
    public List<UserVo> q2(String name,String password){  
        logger.info("q2 开始");  
        logger.info("q2接收参数name={},password={}",name,password);  
        return userService.findByNameAndPwd(name, password);  
    }  
      
    @RequestMapping("/sort") 
    @ResponseBody 
    public List<UserVo> sort(){  
        logger.info("sort 开始");  
        List<UserVo> people=userService.findAll(new Sort(Direction.ASC,"age"));  
        return people;  
    }  
      
    @RequestMapping("/page") 
    @ResponseBody 
    public Page<UserVo> page(){  
        logger.info("page 开始");  
        Page<UserVo> people=userService.findAll(new PageRequest(1,2));  
        return people;  
    } 
}
